package springboot_shiro.com.ljs.config;

import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import springboot_shiro.com.ljs.entity.Student_boot;
import springboot_shiro.com.ljs.service.impl.StudentService;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

public class Myrealm extends AuthorizingRealm {
    @Resource
    StudentService studentService;//获取数据接口
  /**
       * 授权
       * @param principalCollection
       * @return
       */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前登录的用户信息
        Subject subject= SecurityUtils.getSubject();
        Student_boot student_boot= (Student_boot) subject.getPrincipal();
        System.out.println("角色"+student_boot);
        Set<String> roles = new HashSet<>();
        roles.add(student_boot.getRole());//添加角色
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        Set<String> permis = new HashSet<>();
        permis.add(student_boot.getPermis());
        //设置权限
        info.addStringPermissions(permis);
        return info;


    }
// /**
//  * 认证
//  * @param authenticationToken
//  * @return
//  * @throws AuthenticationException
//  */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) authenticationToken;//强制转换密码令牌
        String username=usernamePasswordToken.getUsername();//获取输入的用户名

        System.out.println("要查找的用户是"+username);

        //获取数据库对象
        Student_boot student_boot=studentService.selByname(username);
        System.out.println("查出来了"+student_boot);
        SimpleAuthenticationInfo simpleAuthenticationInfo=null;
        if(student_boot!=null){
            simpleAuthenticationInfo= new SimpleAuthenticationInfo(student_boot,student_boot.getPassword(),getName());

        }
        return simpleAuthenticationInfo;//返回认证信息
    }
}
